<template>
  <el-form ref="form" :model="form" :rules="rules">
    <el-form-item ref="phone" label="手机号" prop="phone">
      <el-input
        v-model="form.phone"
        placeholder="请输入手机号"
        type="number"
        autofocus
        @keyup.enter.native="signIn"
      />
    </el-form-item>
    <template v-if="signInType === 'password'">
      <el-form-item ref="password" label="密码" prop="password">
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          show-password
          @keyup.enter.native="signIn"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="text" @click="changeSignInType('code')">验证码登录</el-button>
      </el-form-item>
    </template>
    <template v-else>
      <el-form-item ref="code" label="验证码" prop="code">
        <el-input v-model="form.code" placeholder="请输入验证码" @keyup.enter.native="signIn">
          <send-code-btn
            slot="suffix"
            :phone="form.phone"
            class="m-r-10"
            @checkPhone="checkPhone"
          />
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="text" @click="changeSignInType('password')">密码登录</el-button>
      </el-form-item>
    </template>
    <el-form-item>
      <el-button class="full" type="primary" @click="signIn" :loading="loading">登录</el-button>
    </el-form-item>
    <div class="flex align-items-center pointer info-deep f-mini" @click="EduCoderSignIn">
      <el-avatar :src="EduCoderLogo" :size="20" class="m-r-5" />
      EduCoder账号登录
    </div>
  </el-form>
</template>

<script>
import { mapActions } from 'vuex';
import { formatUser } from '@/views/users/format';
import SendCodeBtn from '@/components/shared/SendCodeBtn';
import EduCoderLogo from '@/assets/EduCoder.jpg';

export default {
  name: 'sign-in-form',
  components: { SendCodeBtn },
  data() {
    return {
      form: {
        phone: '',
        password: '',
        code: '',
      },
      rules: {
        phone: [{ validator: this.$va.phone, trigger: 'none' }],
        password: [{ validator: this.$va.password, trigger: 'none' }],
        code: [{ validator: this.$va.code, trigger: 'none' }],
      },
      loading: false,
      EduCoderLogo,
    };
  },
  computed: {
    // 登录方式
    signInType() { return this.$route.query.type || 'password'; },
    // 登录所需参数
    signInParams() {
      return {
        phone: this.form.phone,
        type: this.signInType,
        password: this.form.password,
        code: this.form.code,
      };
    },
  },
  methods: {
    ...mapActions({ setCurUser: 'setCurrentUser' }),
    // 登录
    signIn() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.users.signIn(this.signInParams)
            .then((res) => {
              this.$message.success('登录成功');
              this.setCurUser(formatUser(res.data));
              this.$router.push(this.$route.query.redirect || '/');
            })
            .catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 切换登录方式
    changeSignInType(type) {
      if (this.form.phone) this.$refs.form.validateField('phone'); // 当填写了手机号时，验证这个号码
      else this.$refs.phone.clearValidate(); // 当没有填写手机号时，清除验证提示
      if (this.$refs.password) this.$refs.password.resetField(); // 清除密码和验证提示
      if (this.$refs.code) this.$refs.code.resetField(); // 清除验证码和验证提示
      this.$router.push(`/users/sign_in?type=${type}`);
    },
    // 触发验证手机号的方法
    checkPhone() {
      this.$refs.form.validateField('phone');
    },
    // EduCoder 授权登录
    EduCoderSignIn() {
      this.$api.users.EduCoderSignIn()
        .then((res) => {
          const redirect = this.$route.query.redirect;
          if (redirect) localStorage.setItem('otherSignIn', redirect); // 保存跳转页面
          window.location.href = res.data.url;
        })
        .catch(() => {});
    },
  },
};
</script>

<style></style>
